<template>
  <div ref="chartRef" :style="{ width, height }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, inject, markRaw } from 'vue'
// 通过 inject 接收Echarts
const Echarts = inject('$echarts')
const props = defineProps({
  options: { type: Object, required: true },
  theme: { type: [String, Object], default: 'default' },
  initOptions: { type: Object, default: () => ({}) },
  width: { type: String, default: '100%' },
  height: { type: String, default: '400px' },
  autoresize: { type: Boolean, default: true }
})

const chartRef = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  chartInstance = markRaw(Echarts.init(chartRef.value, props.theme, props.initOptions))
  chartInstance.setOption(props.options)
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return
  chartInstance.setOption(props.options)
}

// 自动调整尺寸
const resizeChart = () => {
  chartInstance?.resize()
}

// 窗口大小变化监听
const handleResize = () => {
  if (props.autoresize) resizeChart()
}
// 生命周期
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
  chartInstance = null
})

// 监听选项变化
watch(() => props.options, updateChart, { deep: true })

// 暴露方法
defineExpose({
  getInstance: () => chartInstance,
  resize: resizeChart
})
</script>
